package com.yycx.module.live.io.agora.utils;

import com.yycx.common.utils.ApiAssert;
import com.yycx.module.live.config.AgoraProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;

/**
 *
 */
@Component
@EnableConfigurationProperties(AgoraProperties.class)
public class SignalingTokenUtil {

    private final AgoraProperties agoraProperties;

    @Autowired
    public SignalingTokenUtil(AgoraProperties agoraProperties) {
        this.agoraProperties = agoraProperties;
    }

    public String getToken(String account, int expiredTsInSeconds) {
        String token_String = "";
        try {
            expiredTsInSeconds = expiredTsInSeconds + (int) (new Date().getTime() / 1000L);
            String appId = agoraProperties.getAppId();
            System.out.println("appId:" + appId);
            String certificate = agoraProperties.getCertificate();
            System.out.println("certificate:" + certificate);
            System.out.println("expiredTsInSeconds:" + expiredTsInSeconds);
            StringBuilder digest_String = new StringBuilder().append(account).append(appId).append(certificate).append(expiredTsInSeconds);
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.update(digest_String.toString().getBytes());
            byte[] output = md5.digest();
            String token = hexlify(output);
            token_String = new StringBuilder().append("1").append(":").append(appId).append(":").append(expiredTsInSeconds).append(":").append(token).toString();
            System.out.println("token_String:" + token_String);
        } catch (NoSuchAlgorithmException e) {
            ApiAssert.failure("rmtToken生成错误");
            e.printStackTrace();
        }
        return token_String;
    }

    public String hexlify(byte[] data) {

        char[] DIGITS_LOWER = {'0', '1', '2', '3', '4', '5',
                '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
        char[] toDigits = DIGITS_LOWER;
        int l = data.length;
        char[] out = new char[l << 1];
        // two characters form the hex value.
        for (int i = 0, j = 0; i < l; i++) {
            out[j++] = toDigits[(0xF0 & data[i]) >>> 4];
            out[j++] = toDigits[0x0F & data[i]];
        }
        return String.valueOf(out);
    }
}
